package net.bitacademy.java22.service;

import net.bitacademy.java22.domain.ProfileVO;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class SwHandler extends Trigger {
	boolean connectflag = true;
	ConnectThread connectThread = new ConnectThread();
	public String robotDance() {
  		try {
  			Log.d("Robot", "댄스시작");
  			String a = robot.dance();
  			if(a == null){
  				Log.d("Robot", "error");
  				a = "error";
  			} else
  				Log.d("Robot", "없음");
  			return a;
  		} catch (RemoteException e) {
  			e.printStackTrace();
  			Log.d("Robot", "댄스Rmx");
  		}
		return null;
	}
	
	public String connect(){
		try {
			Log.d("Robot", "커넥시작");
			String a=robot.connect();
			return "connect";
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "에러";
		}
	}
	
	public String disconnect(){
		try {
			Log.d("Robot", "디스커넥");
			String a=robot.disconnect();
			return a;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "에러";
		}
	}
	
	public int getStatus(){
		try {
			Log.d("Robot", "상태");
			int a=robot.getStatus();
			return a;
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 5;
		}
	}
	
	public void goSoftwareSetting(ProfileVO pvo) {
		
		boolean bluetooth = Trigger.mBluetoothAdapter.isEnabled();
		if(bluetooth != true){
			Trigger.mBluetoothAdapter.enable();
		}
		
		try { Thread.sleep(3000);} catch (Exception e) { e.printStackTrace(); }
		
		String flag = pvo.getSwflag();
		if(flag.equals("On")){
			
			connectThread.start();
		}
	}
	

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private class ConnectThread extends Thread {
		@Override
		public void run() {
			//super.run();
			connect();
			while(connectflag) {
				try {
					if(getStatus()==0) {
						connect();
					} else if(getStatus()==1) {
						Log.d("Robot", "connecting");
					} else if(getStatus()==2) {
						robotDance();
						connectflag=false;
						connectThread.stop();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				try { Thread.sleep(10000);} catch (Exception e) { e.printStackTrace(); }
				
			}
		}
	}
}
